<template>
	<el-table :data="userRoleData">
		<el-table-column prop="uname" label="用户名称">
			
		</el-table-column>
		<el-table-column prop="rName" label="角色名称">
			
		</el-table-column>
		<el-table-column label="操作">
			<template #default="scope">
				
				<el-button type="warning" @click="update(scope.row)">
					配置用户角色
				</el-button>
				
			</template>
		</el-table-column>
	</el-table>
	<el-dialog
	    v-model="dialogVisible_update"
	    title="配置用户角色"
	    width="30%"
	  >
	  <el-select
	        v-model="role_value"
	        placeholder="Select"
	        size="large"
	        style="width: 240px"
			multiple
			@change="selectChange"
			value-key="id"
	      >
	        <el-option
	          v-for="item in options"
	          :key="item.id"
	          :label="item.name"
	          :value="item.id"
	        />
	      </el-select>
	    <template #footer>
	      <span class="dialog-footer">
	        <el-button @click="dialogVisible_update = false">Cancel</el-button>
	        <el-button type="primary" @click="updateSubmit"
	          >Confirm</el-button
	        >
	      </span>
	    </template>
	  </el-dialog>
</template>

<script setup>
	import {ref} from 'vue'
	import http from './request.js'
	const userRoleData = ref([])
	const dialogVisible_update = ref(false)
	const uid = ref(undefined)
	function query(){
		http.get('/userRole/select').then(res=>{
			userRoleData.value = res.data
		})
	}
	query()
	function update(e){
		uid.value = e.uid
		role_value.value = []
		role_value_cache.value = []
		if(e.rid){
			role_value.value = e.rid.split(',').map(Number)
			role_value_cache.value = e.rid.split(',').map(Number)
		}
		dialogVisible_update.value = true
		queryRole()
	}
	function updateSubmit(){
		// 表中需要添加的
		let needAdd = []
		// 表中需要删除的
		let needDel = []
		needAdd = role_value.value.map(item=>{
			if(!role_value_cache.value.includes(item)){
				return item
			}
		}).filter(item => item !== undefined)
		needDel = role_value_cache.value.map(item=>{
			if(!role_value.value.includes(item)){
				return item
			}
		}).filter(item => item !== undefined)
		console.log(needAdd,needDel)
		http.post('/userRole/addAndDel',{userId:uid.value,needAdd,needDel}).then(res=>{
			query()
			dialogVisible_update.value = false
		})
	}
	const options = ref([])
	const role_value = ref(undefined)
	const role_value_cache = ref(undefined)
	function queryRole(){
		http.get('/roles/queryAll').then(res=>{
			options.value = res.data
		})
	}
	function selectChange(e){
		console.log(e)
	}
</script>

<style>
</style>